package cp5_jdbc.servlet;

import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.util.Enumeration;
import java.util.Properties;

@WebServlet("/cp5/jdbc_test")
public class JDBCTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "123456";

        PrintWriter out = StringUtil.getWriter(resp);

        try {
            // 1. 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");//mysql的jdbc驱动名称
            // 2.获取连接
            Connection conn = DriverManager.getConnection(url, username, password);
            DatabaseMetaData metaData = conn.getMetaData();
            String databaseProductVersion = metaData.getDatabaseProductVersion();
            out.println("数据库的版本信息:" + databaseProductVersion + "<br>");
            // 通过连接获取客户端信息
            Properties clientInfo = conn.getClientInfo();
            Enumeration<Object> keys = clientInfo.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement().toString();
                String value = clientInfo.getProperty(key);
                out.println("key:" + key + "==>value:" + value + "<br>");
            }
            // 3.关闭连接
            conn.close();
        } catch (Exception e) {
            out.println("异常了:" + e.getMessage());
        }
    }
}
